 /*
 *问答题收集
  */
<template>
  <div id="select_topic">
    <div>
      <!-- 选择题题目 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>
            三 、问答题 ( 本题共{{form.questionInfo.length}}道小题,共
            <span class="topic-grade">{{selectTopicM}}/{{sum}}</span>分 )
          </span>
        </div>
        <div v-for="(item,index) in form.questionInfo " :key="index">
          <el-form ref="form" :model="item" label-width="80px">
            <el-form-item :label="index+1 +'、'" v-show="!item.editing">
              <!-- 问题 -->
              <span>{{item.tpqQuestion.questionTitle}}</span>
              <el-input-number v-model="item.tpqScore" :min="1" :max="50" size="mini" @change="scoreChange(item)"></el-input-number>
            </el-form-item>
            <el-form-item :label="index+1 +'、'" v-show="item.editing">
              <el-input type="textarea" v-model="item.tpqQuestion.questionTitle" autosize></el-input>
            </el-form-item>
            <el-form-item>
              <span class="reference">参考答案</span>
            </el-form-item>
            <!-- 回答 -->
            <el-form-item v-show="!item.editing" >
              <span v-html="item.tpqQuestion.answerQuestion.aqAnswer"></span>
            </el-form-item>
            <!-- 富文本 -->
            <el-form-item v-show="item.editing">
              <editor
                class="tinymce"
                v-model="item.tpqQuestion.answerQuestion.aqAnswer"
                :init="init"
              ></editor>
            </el-form-item>
            <el-form-item>
              <el-button size="small" round @click="compileTopic(item)">编辑</el-button>
              <el-button size="small" round v-show="item.editing" @click="cancelCompileTopic(index)">取消</el-button>
              <el-button
                size="small"
                @click="changTopicAnswer(item)"
                type="primary"
                round
                v-show="item.editing"
                plain
              >保存修改</el-button>
              <el-button
                size="small"
                @click="deleTopic(index)"
                round
                v-show="item.editing"
                type="danger"
                plain
              >删除题目</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import tinymce from "tinymce/tinymce"; //引入tinymce富文本插件
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver";
import "tinymce/plugins/image"; // 插入上传图片插件
import "tinymce/plugins/table"; // 插入表格插件
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/wordcount"; // 字数统计插件
import "tinymce/plugins/fullscreen"; //全屏插件
import "tinymce/plugins/preview"; //预览插件
import "tinymce/plugins/code"; //源代码插件
import "tinymce/plugins/wordcount"; //字数插件
import "tinymce/plugins/autoresize"; //高度自适应
import "tinymce/plugins/paste"; // 允许粘贴文本
export default {
  props: ["teStPaperInfo","sum"],
  components: {
    Editor
  },
  data() {
    return {
      sumMin:0,//最小分值
      primeval: {}, //初始值
      form: {//表单信息
        questionInfo: [] //题目信息
      },
      init: {
        language_url: "/tinymce/zh_CN.js", // 语言包的路径
        language: "zh_CN", //语言
        skin_url: "/tinymce/skins/ui/oxide", // skin路径
        height: this.height, //编辑器高度
        branding: false, //是否禁用“Powered by TinyMCE”
        menubar: false, //顶部菜单栏显示
        // inline: true,
        selector: "textarea", //指定CSS选择器
        plugins:
          "lists image table wordcount fullscreen preview code wordcount autoresize paste", //插件
        autoresize_bottom_margin: 50, // 编辑器的底部外边距
        autoresize_max_height: 800, // 编辑区域的最大高
        autoresize_min_height: 350, // 编辑区域的最小高
        autoresize_on_init: true, //自适应高度
        paste_as_text: true, // 允许粘贴文本
        //工具栏
        toolbar:
          "undo redo |  formatselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image table | removeformat | fullscreen | preview | code | wordcount",
        /* blobinfo参数是一个对象,包含上传文件的信息,success为成功函数,上传成功的时候向 success 传入一个图片地址，失败的时候向 failure 传入报错信息 */
        images_upload_handler: (blobInfo, success, failure) => {
          //上传图片
          this.modifyingHead(blobInfo, success, failure);
        }
      }
    };
  },
  methods: {
    //上传图片
    modifyingHead(blobInfo, success, failure) {
      let that = this;
      let formdata = new FormData();
      formdata.set("upload_file", blobInfo.blob());
      // 请求接口
      that.axios
        .post("/api/Question/UploadImg", formdata)
        .then(res => {
          success(res.data.location);
        })
        .catch(error => {
          failure(error);
        });
    },
    // 编辑题目
    compileTopic(item) {
      item.editing = true;//更改编辑状态
      item.primeval = JSON.parse(JSON.stringify(item));//存储初始信息
    },
    //取消编辑
    cancelCompileTopic(i){
      let prime=this.form.questionInfo[i].primeval //获取初始值
      prime.editing = false;
      this.$set(this.form.questionInfo, i, prime);//将初始值赋值回数组中
    },
    //保存修改题目
    changTopicAnswer(item) {
      let _this = this;
      console.log(item)
      let newItemTitle = item.tpqQuestion.questionTitle; //新题干
      let newItemAqAnswer = item.tpqQuestion.answerQuestion.aqAnswer; //答案
      if (!newItemTitle.trim() || !newItemAqAnswer.trim()) {
        _this.$message.warning("请输入答案和题目名称");
      } else {
          _this.axios
            .post("/api/TestPaper/ModifyQuestion", {
              questionId: item.tpqQuestion.questionId, //题目ID
              questionTitle: item.tpqQuestion.questionTitle, //题目标题
              questionTypeId: item.tpqQuestion.questionTypeId, //题目类型  1选择题  2填空题 3问答题
              answerQuestion: item.tpqQuestion.answerQuestion //答案
            })
            .then(res => {
              if (res.data.code == 1){ 
                _this.form.questionInfo.forEach(newItem => {
                  if (newItem.tpqId == item.tpqId) { //修改数组数据
                    newItem = item;
                    item.editing = false;
                    _this.$message.success("修改成功");
                  }
                });
              }else{
                _this.$message.warning(res.data.message);
              }
            })
            .catch(e => {
              console.log(e);
            });
      }
    },
    // 删除题目
    deleTopic(i) {
      let _this = this;
      _this
        .$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          _this.axios
            .post(
              "/api/TestPaper/RemoveQuestionFromTestPaper?paperQuestionId=" +
                _this.form.questionInfo[i].tpqId //题目ID
            )
            .then(res => {
              if (res.data.code == 1) {
                _this.form.questionInfo.splice(i,1) //更新数据
                _this.$message.success("删除成功!")
              }
            })
            .catch(e => {
              console.log(e);
            });
        })
        .catch(() => {
          _this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    scoreChange(obj) {
      //修改分数方法
      this.axios.post("/api/TestPaper/ModifyScore", {
        tpqId: obj.tpqId, //主键编号
        tpqScore:obj.tpqScore, //小题分数
      }).then(res => {
        if (res.data.code == 1) {
          //请求数据，判断返回状态
          this.$message.success(res.data.message);
        } else {
          this.$message.info(res.data.message);
        }
      });
    },
    questiTopicM(){
      this.$emit("questiTopicM",this.selectTopicM)
    }
  },
  watch: {
    teStPaperInfo(newVal) {
      console.log(newVal)
      //把父组件传过来的数据转换为字符串 ---- 这转换为对象 ---就可以进行操作了
      let newVal1 = JSON.parse(JSON.stringify(newVal));
       this.form.questionInfo=newVal1.questions.filter(item=>item.tpqQuestion.questionTypeId == 3);//过滤问题类型
    }
  },
  updated(){
  this.questiTopicM()
  },
  computed: {
    //选择题小题分数
    selectTopicM() {
      let _this = this;
      // 迭代所有的元素最终返回一个值
      let m = _this.form.questionInfo.reduce((sum, item) => {
        return sum + item.tpqScore;
      }, 0);
      return m;
    }
    
  },
  mounted() {
    tinymce.init({});
  }
};
</script>
<style lang="less" scoped>
.reference {
  background-color: #f4f4f5;
  border-radius: 4px;
  width: 60px;
  height: 25px;
  display: block;
  line-height: 25px;
  text-align: center;
  font-size: 12px;
  color: #909399;
}
// 选择题目试卷类容
.topic-grade {
  background-color: #f56c6c;
  border-radius: 10px;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  text-align: center;
  white-space: nowrap;
  border: 1px solid #fff;
}
</style>